package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os/exec"
	"runtime"
	"strconv"
	"time"
)

// openBrowser 打开默认浏览器访问指定URL
func openBrowser(url string) {
	var cmd *exec.Cmd
	switch runtime.GOOS {
	case "windows":
		cmd = exec.Command("cmd", "/c", "start", url)
	case "darwin":
		cmd = exec.Command("open", url)
	default:
		cmd = exec.Command("xdg-open", url)
	}
	if err := cmd.Run(); err != nil {
		log.Println("Failed to open browser:", err)
	}
}
func main() {

	// 设置HTTP服务器路由
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		content, err := ioutil.ReadFile("index.html")
		if err != nil {
			http.Error(w, "Failed to load page", http.StatusInternalServerError)
			log.Println("Error reading index.html:", err)
			return
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Write(content)
	})

	// 新增关机路由
	http.HandleFunc("/shutdown", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
			return
		}
		log.Println("Shutdown request received. Shutting down the system...")
		go executeCommand("shutdown")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("Shutdown request processed"))
	})

	// 新增重启路由
	http.HandleFunc("/restart", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
			return
		}
		log.Println("Restart request received. Restarting the system...")
		go executeCommand("restart")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("Restart request processed"))
	})

	// 新增定时关机路由
	http.HandleFunc("/shutdown-timer", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
			return
		}
		if err := r.ParseForm(); err != nil {
			http.Error(w, "Failed to parse form data", http.StatusBadRequest)
			return
		}
		minutesStr := r.FormValue("minutes")
		if minutesStr == "" {
			http.Error(w, "Minutes parameter is required", http.StatusBadRequest)
			return
		}
		minutes, err := strconv.Atoi(minutesStr)
		if err != nil || minutes <= 0 {
			http.Error(w, "Invalid minutes value", http.StatusBadRequest)
			return
		}
		log.Printf("Scheduled shutdown in %d minutes...\n", minutes)
		time.AfterFunc(time.Duration(minutes)*time.Minute, func() {
			log.Println("Executing scheduled shutdown...")
			executeCommand("shutdown")
		})
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(fmt.Sprintf("Scheduled shutdown in %d minutes", minutes)))
	})

	// 注册重启定时器的路由
	http.HandleFunc("/restart-timer", restartTimerHandler)

	// 启动HTTP服务器
	go func() {
		log.Println("Starting server at port 8080")
		if err := http.ListenAndServe(":8080", nil); err != nil {
			log.Fatal(err)
		}
	}()

	// 新增：启动后自动打开浏览器
	openBrowser("http://localhost:8080")

	// 阻塞主函数，防止服务退出
	select {}
}

// executeCommand 执行系统命令
func executeCommand(action string) {
	var cmd *exec.Cmd
	switch runtime.GOOS {
	case "windows":
		if action == "shutdown" {
			cmd = exec.Command("shutdown", "/s", "/t", "0")
		} else if action == "restart" {
			cmd = exec.Command("shutdown", "/r", "/t", "0")
		}
	case "darwin":
		if action == "shutdown" {
			cmd = exec.Command("sudo", "shutdown", "-h", "now")
		} else if action == "restart" {
			cmd = exec.Command("sudo", "reboot")
		}
	default:
		if action == "shutdown" {
			cmd = exec.Command("sudo", "poweroff")
		} else if action == "restart" {
			cmd = exec.Command("sudo", "reboot")
		}
	}
	if cmd != nil {
		if err := cmd.Run(); err != nil {
			log.Println("Failed to execute command:", err)
		}
	}
}

// 新增定时重启功能的处理逻辑
func restartTimerHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}

	// 解析表单数据
	err := r.ParseForm()
	if err != nil {
		http.Error(w, "Failed to parse form data", http.StatusBadRequest)
		return
	}

	// 获取定时重启的时间（分钟）
	minutesStr := r.Form.Get("minutes")
	minutes, err := strconv.Atoi(minutesStr)
	if err != nil || minutes <= 0 {
		http.Error(w, "Invalid minutes value", http.StatusBadRequest)
		return
	}

	// 设置定时重启
	go func() {
		time.Sleep(time.Duration(minutes) * time.Minute)
		executeCommand("restart")
	}()

	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "System will restart in %d minutes", minutes)
}
